<?php

class DocumentController extends Zend_Controller_Action
{

  public function init()
  {
  }

  public function indexAction()
  {
    /**
     * @var $documentTable Application_Model_DbTable_Documents
     */
    $documentTable = Engine_Api::_()->getDbTable('documents', 'application');
    $this->view->documents = $documents = $documentTable->fetchAll($documentTable->select()
      ->from($documentTable->info('name'), array('document_id', 'title'))
    );
  }

  public function viewAction()
  {
    $id = $this->getRequest()->getParam('document_id');
    if ($id) {
      $this->view->document = $document = new Application_Model_Document($id);
    } else {
      $this->view->error = 'Нет документа с таким ID';
    }
  }

  public function createAction()
  {
    $viewer = Engine_Api::_()->application()->getViewer();
    if (!$viewer)
      return;
    $this->view->form = $form = new Application_Form_Document();
    $this->view->title = 'Создание нового документа';
    if ($this->getRequest()->isPost()) {
      $data = $this->getRequest()->getPost();
      if ($form->isValid($data)) {
        $document = new Application_Model_Document();
        $document->fill($data);
        $document->user_id = $viewer->user_id;
        $document->creation_date = date("Y-m-d H:i:s");
        $document->modified_date = date("Y-m-d H:i:s");
        $document->save();
        $this->redirect('document/view/document_id' . $document->document_id);
      }
    }
  }

  public function editAction()
  {
    $id = $this->getRequest()->getParam('document_id');
    if ($id) {
      $document = new Application_Model_Document($id);
    } else {
      $this->view->error = 'Нет документа с таким ID';
      return;
    }
    $viewer = Engine_Api::_()->application()->getViewer();
    if (!$viewer)
      return;
    $this->view->form = $form = new Application_Form_Document();
    $this->view->title = 'Создание нового документа';
    if ($this->getRequest()->isPost()) {
      $data = $this->getRequest()->getPost();
      if ($form->isValid($data)) {
        $document->fill($data);
        $document->modified_date = date("Y-m-d H:i:s");
        $document->save();
        $this->redirect('document/view/document_id' . $document->document_id);
      }
    }
    $form->populate(array('title' => $document->title, 'body' => $document->body));
  }
}



